//
//  SDView.m
//  CWeekly
//
//  Created by Tiger on 12-4-12.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SDView.h"
#import "DataProvider.h"
#import "AppDelegate.h"
#import <QuartzCore/QuartzCore.h>
#define HEIGHT_S 1024-75-78
#define HEIGHT_H 768-75-78
#define HEIGHT_S_2 (1024-75-78)/2
#define HEIGHT_H_2 (768-75-78)/2

@implementation SDView

- (id)initWithH:(BOOL)isH
{
    self = [super init];
    if (self) {
        // Initialization code
        
        [[NSNotificationCenter defaultCenter] addObserver: self 
												 selector: @selector(reflashList) 
													 name: @"ReflashShangdianList" 
												   object: nil ];
        [[NSNotificationCenter defaultCenter] addObserver: self 
												 selector: @selector(searchSelect:) 
													 name: @"searchSelect" 
												   object: nil ];
        
        _isH = isH;
        self.autoresizesSubviews = NO;
        bookList = [[NSMutableArray alloc]init];
        bufferList = [[NSMutableArray alloc]init];
        senderArray=[[NSMutableArray alloc] init];
        currentPage = 0;
        
        scrollView = [[UIScrollView alloc]init];
        scrollView.backgroundColor = [UIColor clearColor];
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.pagingEnabled = YES;
        scrollView.delegate = self;
        [self addSubview:scrollView];
        
        if (_isH) {
            self.frame = CGRectMake(0, 55, 1024, HEIGHT_H);
        }
        else {
            self.frame = CGRectMake(0, 55, 768, HEIGHT_S);
        }
        
        pageControl = [[UIPageControl alloc]init];
        [self addSubview:pageControl];
        
        [NSThread detachNewThreadSelector:@selector(loadData) toTarget:self withObject:nil];
    }
    return self;
}

- (void)dealloc
{
    //下载
    [senderArray release];
    [scrollView release];
    [pageControl release];
    [bookList release];
    [super dealloc];
}

- (void)cancelDownloadImage
{
	[bufferList makeObjectsPerformSelector:@selector(cancel)];
}

- (void)loadData
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    
    DataProvider *dp = [DataProvider sharedManager];
    DPData *dpData = [dp getBookList];
    
    if (dpData.isSuccess) {
        if ([[dpData.data objectForKey:@"json"] count]>0) {
            [bookList addObjectsFromArray:[dpData.data objectForKey:@"json"]];
            [[NSUserDefaults standardUserDefaults] setValue:bookList forKey:@"BOOKS"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        else {
            NSArray*tempBooklist=[[NSUserDefaults standardUserDefaults] valueForKey:@"BOOKS"];
            [bookList addObjectsFromArray:tempBooklist];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle: nil 
                                                           message: @"无数据"
                                                          delegate: self 
                                                 cancelButtonTitle: @"确定" 
                                                 otherButtonTitles: nil];
            [alert show];
            [alert release];
        }
        [self performSelectorOnMainThread:@selector(loadEnd) withObject:nil waitUntilDone:NO];

    }
    else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: nil 
                                                       message: dpData.data
                                                      delegate: self 
											 cancelButtonTitle: @"确定" 
                                             otherButtonTitles: nil];
		[alert show];
		[alert release];
    }
    [pool release];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ClearLoadingImage" object: nil];
}

- (void)reflashList
{
    for (UIView *v in [scrollView subviews])
    {
        [v removeFromSuperview];
    }
    
    [self performSelectorOnMainThread:@selector(loadEnd) withObject:nil waitUntilDone:NO];
}

- (void)loadEnd
{
    totalCount = [bookList count];
    totalPage = (int)ceil((CGFloat)totalCount/4.0);
    
    pageControl.backgroundColor = [UIColor clearColor];
    pageControl.numberOfPages = totalPage;
    pageControl.currentPage = currentPage;
    
    if (_isH) {
        scrollView.frame = CGRectMake(0, 0, 1024, HEIGHT_H);
        scrollView.contentSize = CGSizeMake(1024*totalPage, HEIGHT_H);
        pageControl.frame = CGRectMake(0, HEIGHT_H,1024, 20);
    }
    else {  
        scrollView.frame = CGRectMake(0, 0, 768, HEIGHT_S);
        scrollView.contentSize = CGSizeMake(768*totalPage, HEIGHT_S);
        pageControl.frame = CGRectMake(0, HEIGHT_S,768, 20);
    }
    
    for (int i=0; i<totalCount; i++) {

        UIImageView *book = [[UIImageView alloc]init];
        book.tag = 1000+i;
        book.layer.borderColor=[[UIColor blackColor] colorWithAlphaComponent:0.6].CGColor;
        book.layer.borderWidth=2;
        book.layer.shadowOffset = CGSizeMake(2, 2);
        book.layer.shadowRadius = 1.0;
        book.layer.shadowColor = [UIColor blackColor].CGColor;
        book.layer.shadowOpacity = 0.8;
        book.image=[UIImage imageNamed:@"smallloading_v.png"];
        [scrollView addSubview:book];
        [book release];
        
        NSString *strUrl = [NSString stringWithFormat:IMAGE_URL,[[bookList objectAtIndex:i] objectForKey:@"mgImg"]];
		
		ImageDownloader *imageDownloader = [[ImageDownloader alloc]initWithUrl:strUrl index:i];
		imageDownloader.delegate = self;
		UIImage *image = [imageDownloader getImage];
		if (nil == image) {
			image = [UIImage imageNamed:@"smallloading_v.png"];//默认图片
			[bufferList addObject:imageDownloader];
		}
		[imageDownloader release];
		book.image = image;

        UIView *infoView = [[UIView alloc]init];
        infoView.backgroundColor = [UIColor clearColor];
        infoView.tag = 5000+i;
        [scrollView addSubview:infoView];
        [infoView release];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, 270, 20)];
        label.text = [[bookList objectAtIndex:i] objectForKey:@"mgTitle"];
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont systemFontOfSize:20.0];
        [infoView addSubview:label];
        [label release];
        
//        NSString *str = [NSString stringWithFormat:@"%@ 第%@期/%@日出版/总第%@期",
//                         [[bookList objectAtIndex:i] objectForKey:@"mgYear"],
//                         [[bookList objectAtIndex:i] objectForKey:@"mgTime"],
//                         [[[[bookList objectAtIndex:i] objectForKey:@"mgIssue"] substringFromIndex:5] stringByReplacingOccurrencesOfString:@"-" withString:@"月"],
//                         [[bookList objectAtIndex:i] objectForKey:@"mgTotal"]];
        label = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, 270, 20)];
        label.text = [[bookList objectAtIndex:i] objectForKey:@"mgPeriod"];
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont systemFontOfSize:15.0];
        [infoView addSubview:label];
        [label release];
        
//        label = [[UILabel alloc]initWithFrame:CGRectMake(0, 65, 270, 80)];
//        label.text = [NSString stringWithFormat:@"　　%@",[[bookList objectAtIndex:i] objectForKey:@"mgDescribe"]];
//        label.textColor = [UIColor whiteColor];
//        label.numberOfLines = 0;
//        label.backgroundColor = [UIColor clearColor];
//        label.font = [UIFont systemFontOfSize:20.0];
//        [infoView addSubview:label];
//        [label release];
        
        UIButton *btnRead = [UIButton buttonWithType:UIButtonTypeCustom];
        
        NSString *title = @"立即下载";
        NSMutableArray *shujia = [[NSMutableArray alloc]init];
        AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        if ([[appDelegate getShujiaList] count]>0) {
            [shujia addObjectsFromArray:[appDelegate getShujiaList]];
        }
        
        NSString *str1 = [NSString stringWithFormat:@"%@",[[bookList objectAtIndex:i] objectForKey:@"mgId"]];
        for (int j=0; j<[shujia count]; j++) {
            
            NSString *str2 = [NSString stringWithFormat:@"%@",[[shujia objectAtIndex:j] objectForKey:@"mgId"]];
            if ([str1 isEqualToString:str2]) {
                title = @"正在下载";
                btnRead.enabled = NO;
                
                NSString *rootPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/BookData"];
                NSString *bookPath = [rootPath stringByAppendingPathComponent:str1];
                
                //Test
                //NSString *rootPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/TempData"];
                //NSString *bookPath = [rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",str1]];
                
                if ([[NSFileManager defaultManager] fileExistsAtPath:bookPath]) {
                    title = @"点击阅读";
                    btnRead.enabled = YES;
                }
            }
        }
        [shujia release];
        
        btnRead.tag = 10000+i;
        [btnRead setTitle:title forState:UIControlStateNormal];
        [btnRead setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btnRead.titleLabel.font = [UIFont boldSystemFontOfSize:14.0];
        [btnRead addTarget:self action:@selector(btnBuy:) forControlEvents:UIControlEventTouchUpInside];
        [btnRead setBackgroundImage:[UIImage imageNamed:@"blank_read_btn.png"] forState:UIControlStateNormal];
        [scrollView addSubview:btnRead];
        [senderArray addObject:btnRead];
        
        if (_isH) {
            book.frame = CGRectMake((i/4)*1024+(i%2)*512+50, ((i%4)/2)*HEIGHT_H_2+50, 160, 200);
            infoView.frame = CGRectMake((i/4)*1024+(i%2)*512+230, ((i%4)/2)*HEIGHT_H_2+50,250, 200);
            btnRead.frame = CGRectMake((i/4)*1024+(i%2)*512+230, ((i%4)/2)*HEIGHT_H_2+220, 85, 35);
            book.layer.shadowPath = [UIBezierPath bezierPathWithRect:book.bounds].CGPath;	

        }
        else {  
            book.frame = CGRectMake((i/4)*768+(i%2)*384+50, ((i%4)/2)*HEIGHT_S_2+50, 160, 200);
            infoView.frame = CGRectMake((i/4)*768+(i%2)*384+50, ((i%4)/2)*HEIGHT_S_2+270,300, 200);
            btnRead.frame = CGRectMake((i/4)*768+(i%2)*384+230, ((i%4)/2)*HEIGHT_S_2+50, 85, 35);
            book.layer.shadowPath = [UIBezierPath bezierPathWithRect:book.bounds].CGPath;	

        }
    }
}

- (void)imageDidFinishLoad:(UIImage *)image index:(NSInteger)index
{
	if (image) {
		UIImageView *imageView = (UIImageView *)[scrollView viewWithTag:1000+index];
		imageView.image = image;
	}
}
- (void)searchSelect:(NSNotification*)nofity{
    NSNumber* n=[nofity object];
    UIButton* btn=[senderArray objectAtIndex:n.intValue];
    [self btnBuy:btn];
}
- (void)btnBuy:(UIButton *)sender
{
    NSInteger index = sender.tag - 10000;
    NSMutableDictionary *book = [bookList objectAtIndex:index];
    if ([sender.titleLabel.text isEqualToString:@"立即下载"]) {
        sender.enabled = NO;
        
        if (book) {
            AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
            NSMutableArray *list = [appDelegate getShujiaList];
            //[list insertObject:book atIndex:0];
            [list addObject:book];
            [appDelegate setShujiaList:list];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ReflashShujiaTable" object: nil];
            [sender setTitle:@"正在下载" forState:UIControlStateNormal];
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle: nil 
                                                           message: @"成功加入到书架" 
                                                          delegate: self 
                                                 cancelButtonTitle: @"确定" 
                                                 otherButtonTitles: nil];
            [alert show];
            [alert release];
        }
    }
    else if ([sender.titleLabel.text isEqualToString:@"点击阅读"]){
        NSMutableDictionary *object = [NSMutableDictionary dictionary];
        [object setValue:[book valueForKey:@"mgId"] forKey:@"mgId"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"ToDetaiViewController" object:object];
    }
    //[self reflashList];
}

- (void)scrollViewDidScroll:(UIScrollView *)_scrollView
{
    CGPoint p = scrollView.contentOffset;
    
    CGFloat width = 0.0;
    if (_isH) {
        width = 1024;
    }
    else {  
        width = 768;
    }
    
    currentPage = floor((p.x - width / 2) / width) + 1;
    pageControl.currentPage = currentPage;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    for (UILabel *book in [scrollView subviews]) {
        if (book.tag<5000) {
            NSInteger i = book.tag - 1000;
            if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
                book.frame = CGRectMake((i/4)*1024+(i%2)*512+50, ((i%4)/2)*HEIGHT_H_2+50, 160, 200);
            }
            else {  
                book.frame = CGRectMake((i/4)*768+(i%2)*384+50, ((i%4)/2)*HEIGHT_S_2+50, 160, 200);
            }
        }
    }
    
    for (UIView *infoView in [scrollView subviews]) {
        if (infoView.tag>=5000 && infoView.tag<10000) {
            NSInteger i = infoView.tag - 5000;
            if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
                infoView.frame = CGRectMake((i/4)*1024+(i%2)*512+230, ((i%4)/2)*HEIGHT_H_2+50,250, 200);
            }
            else {  
                infoView.frame = CGRectMake((i/4)*768+(i%2)*384+50, ((i%4)/2)*HEIGHT_S_2+270,300, 200);
            }
        }
    }
    
    for (UIButton *btnRead in [scrollView subviews]) {
        if (btnRead.tag>=10000 && btnRead.tag<15000) {
            NSInteger i = btnRead.tag - 10000;
            if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
                btnRead.frame = CGRectMake((i/4)*1024+(i%2)*512+230, ((i%4)/2)*HEIGHT_H_2+220, 85, 35);
            }
            else {  
                btnRead.frame = CGRectMake((i/4)*768+(i%2)*384+230, ((i%4)/2)*HEIGHT_S_2+50, 85, 35);
            }
        }
    }
    
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        scrollView.frame = CGRectMake(0, 0, 1024, HEIGHT_H);
        scrollView.contentSize = CGSizeMake(1024*totalPage, HEIGHT_H);
        [scrollView setContentOffset:CGPointMake(currentPage*1024, 0) animated:YES];
        pageControl.frame = CGRectMake(0, HEIGHT_H,1024, 20);
        
        self.frame = CGRectMake(0, 55, 1024, HEIGHT_H);
        _isH = YES;
    }
    else {  
        scrollView.frame = CGRectMake(0, 0, 768, HEIGHT_S);
        scrollView.contentSize = CGSizeMake(768*totalPage, HEIGHT_S);
        [scrollView setContentOffset:CGPointMake(currentPage*768, 0) animated:YES];
        pageControl.frame = CGRectMake(0, HEIGHT_S,768, 20);
        
        self.frame = CGRectMake(0, 55, 768, HEIGHT_S);
        _isH = NO;
    }
}

@end
